import { defineStore } from "pinia";
import EventBus from "@/utils/EventBus";
import { getCodeApi, LoginApi } from '@/Api/Login'

export const useLogin = defineStore('Login', {
    state: (): LoginState => {
        return {
            token: '',
            user: {} as user,
            loading: false,
            codeSrc: '',
            isLogin: false,
            userFormData: {
                login: '',
                password: '',
                verCode: ''
            },
        }
    },
    getters: {},
    actions: {
        async getCode() {
            const Response = await getCodeApi()
            this.codeSrc = 'data:image/png;base64,' +
                window.btoa(
                    new Uint8Array(Response).reduce(
                        (data, byte) => data + String.fromCharCode(byte), ''
                    )
                )
        },
        async Login() {

            this.loading = true
            try {
                const data = await LoginApi(this.userFormData) as unknown as any
                if (data) {
                    new Promise((resolve, reject) => {
                        this.token = data.token.token
                        this.user = data.user
                        this.loading = false
                        this.isLogin = true
                        resolve('')
                    }).then(() => {
                        EventBus.emit('LoginSuccess', data.user.department, data.user.departmentId, data.user.illArea)
                    })
                }
            } catch {
                this.loading = false
                this.getCode()
            } finally {
                this.loading = false
            }
        }
    },
    persist: {
        debug: true,
        storage: sessionStorage,
        paths: ['token', 'user']
    }
})